<template>
  <div>
    <van-nav-bar title="登录" />
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <!-- 
      vant提供的输入框叫van-field
      本项目中name属性没啥用
      label：控制左侧显示的文字
   -->
      <van-field
        v-model="info.mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="info.code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
          loading-text="登录中..."
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'
export default {

  data () {
    return {
      isLoading: false,
      info: {
        // 双向绑定手机号
        mobile: '13199988888',
        // 双向绑定验证码
        code: '246810'
      },
      //规则对象
      rules: {
        mobile: [
          //一条规则就是一条对象
          { required: true, message: '请填写手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }

        ],

        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '请填写6位数字验证码' }
        ]
      }
    }
  },

  methods: {
    async onSubmit () {
      this.isLoading = true
      //调用vuex里面的actions的方法发送异步请求
      //根据vuex里面返回的状态判断登录是否成功
      const result = await this.$store.dispatch('login', this.info)

      
      if (result) {
        //登录成功了，做跳转的判断
        if (this.$route.query.back) {
          this.$router.push(this.$route.query.back)
        } else {
          this.$router.push('./layout/home')
        }

      }
      //不管请求成功或者失败都关掉
      this.isLoading = false
    }
  }

}
</script>

<style>
</style>